<?php
namespace app\blog\controller;
use cmf\controller\AdminBaseController;
use think\Db;

class StoreCatController extends AdminBaseController
{    
    public function index(){
        $cat_list = Db::name('StoreType')->paginate(10);
        // 获取分页显示
        $page = $cat_list->render();
        $this->assign("page", $page);
        $this->assign("cat_list", $cat_list);
        return $this->fetch();
    }
    public function add(){
        $goods_list = Db::name('Goods')->where(array('g_status'=>1))->select()->toarray();
        $this->assign("goods_list", $goods_list);
        return $this->fetch();
    }
    public function addPost(){
        $res  = $this->request->param();
        $g_id_str=implode(',',$res['id_str']);
        
        $data=array(
            'franchise_fee'=>$res['franchise_fee'],
            'cat_name'=>$res['cat_name'],
            'cat_goods'=>$g_id_str,          
        );
        $re=Db::name('StoreType')->insert($data);
        if($re){
            $da['msg']="添加成功！";
        }else{
            $da['msg']="添加失败！"; 
        }
        return $da;
    }
    public function edit(){
        $id  = $this->request->param('id');
        $info = Db::name('StoreType')->where(array('id'=>$id))->find();
        $info['arr']=explode(',',$info['cat_goods']);
        $goods_list = Db::name('Goods')->where(array('g_status'=>1))->select()->toarray();
        $this->assign("goods_list", $goods_list);
        $this->assign("info", $info);
        return $this->fetch();
    }     
    public function editPost(){
        $res  = $this->request->param();
       
        if (!empty($res['id_str'])){
            $g_id_str=implode(',',$res['id_str']);
        }else{
            $da['msg']="请选择商品！";
            return $da;
        }
        $data=array(
            'franchise_fee'=>$res['franchise_fee'],
            'cat_name'=>$res['cat_name'],
            'cat_goods'=>$g_id_str,
        );
        $re=Db::name('StoreType')->where(array('id'=>$res['id']))->update($data);
        if($re){
            $da['msg']="修改成功！";
        }else{
            $da['msg']="修改失败！"; 
        }
        return $da;
    }
    function delete(){
        $id = $this->request->param("id");
        //判断这个类别下有没有店铺
        $check=Db::name('Store')->where(array('cat_store'=>$id))->find();
        if($check){
            $this->error('该类型下面有店铺，不能删除');
            exit;
        }
        $info = Db::name('StoreType')->where(['id' => $id])->find();
        if ($info){
            $status = Db::name('StoreType')->delete($id);
            if (!empty($status)) {
                $this->success("删除成功！", url('StoreCat/index'));
            } else {
                $this->error("删除失败！");
            }
        }else{
            $this->error("该类别不存在！");
        }   
    }
}
